package com.zoran.study.spring.common.advice;


import com.zoran.study.spring.common.CommonErrors;
import com.zoran.study.spring.common.RestError;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Locale;

@ControllerAdvice
public class FrameworkExceptionAdvice extends ExceptionAdvice {

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    public ResponseEntity<RestError> handler415(HttpMediaTypeNotSupportedException e,
                                                Locale locale) {
        return toHttpResponse(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
                CommonErrors.COMMON_UNSUPPORTED_MEDIA_TYPE, locale, e.getContentType(),
                e.getSupportedMediaTypes());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public ResponseEntity<RestError> handler405(HttpRequestMethodNotSupportedException e,
                                                Locale locale) {
        return toHttpResponse(HttpStatus.METHOD_NOT_ALLOWED, CommonErrors.COMMON_METHOD_NOT_ALLOWED,
                locale, e.getMethod(), e.getSupportedHttpMethods());
    }

}
